package controller;

import pojo.Admin;
import service.AdminService;
import service.impl.AdminServiceimpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.8.31 上午 10:26
 */
@WebServlet("/adminlogin")
public class AdminLogin extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /*//处理乱码:post/响应乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");*/
        
        //在前台获取数据
        //获取管理员用户名
        String adminname = request.getParameter("adminname");
        //获取管理员密码
        String adminpassword = request.getParameter("adminpassword");
        //获取验证码
        String code = request.getParameter("code");

        //先处理验证码,验证码存储在服务器端HttpSession

        //获取session
        HttpSession session = request.getSession();

        //从session域获取CHECKCODE_SERVER绑定的内容
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");

        //一次性验证
        session.removeAttribute("CHECKCODE_SERVER");

        if(!code.equalsIgnoreCase(checkcode_server) || code == null){
            request.setAttribute("msg","验证码错误");
            request.getRequestDispatcher("admin/admin_login.jsp").forward(request,response);
        }

        //调用业务接口
        AdminService adminService = new AdminServiceimpl();
        boolean flag = adminService.isLogin(adminname, adminpassword);
        //封装管理员数据
        Admin admin = new Admin(adminname,adminpassword);
        if(flag){
            Cookie cookie = new Cookie("username",adminname);
            cookie.setMaxAge(60*60*24*7);//有效期为一周,cookie时以秒为单位
            response.addCookie(cookie);
            //登录后将Admin实体 存储session域中
            session.setAttribute("admin",admin);

            //跳转页面
            request.getRequestDispatcher("admin/admin_index.jsp").forward(request,response);
        }else {
            request.setAttribute("msg","登录失败");
            request.getRequestDispatcher("admin/admin_login.jsp").forward(request,response);
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);

    }
}
